var App = App||{};
App.Week = {};
App.Week.init = function(){
	this.dayTemplate = $("#dayTemplate").template();
	this.container = $('#wrapper');
	
	$(window).bind('resize', App.Week.adjustStatsBoxes);
};


/*** WEEK ACTIONS **************************************************************************************************************/
App.Week.load = function(from, to, projectId, userIds){
	if (!from) from = $('#fromDate').val();
	if (!to) to = $('#toDate').val();
	if (!projectId) projectId = +$('#projectPlaceholder .project').data('projectId');
	if (!projectId) projectId = 0;
	if (!userIds){
		var inputs = $('#userSelect input:checked'), inp, i=0, ids = [];
		for (; inp = inputs[i++]; ) ids.push(inp.value);
		if (ids.length) userIds = '&userId='+ids.join('&userId=');
		else userIds = '';
	}
	// validation 
	if (!from || !to){ App.Error('Please select date range!'); return; }
	
	$.ajax({ url: "projectWeek", context: this, data: 'from='+from+'&to='+to+'&projectId='+projectId+userIds })
		.success(function(response){
			if (!response || response.result == 'error'){ this.clear(); return App.Error(response); }
			this.populate(response);
		});
};

App.Week.clear = function(data){ this.container.html(''); };

App.Week.populate = function(data){
	var wrapperW = this.container.width(), panelW,
		panel = this.container.find('.week'), newPanel,
		weekHtml = $.tmpl(this.dayTemplate, data);
	
	if(!weekHtml.length) return msgerror('No data found. Try a different criteria.');

	newPanel = $('<div class="week"/>').append(weekHtml);
	newPanel.find('.day').each(function(){
		$('.row:even', this).addClass('even');

		$('.row-type-1:first', this).addClass('row-type-1-img');
		$('.row-type-1:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');
		
		$('.row-type-2:first', this).addClass('row-type-2-img');
		$('.row-type-2:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');

		$('.row-type-3:first', this).addClass('row-type-3-img');
		$('.row-type-3:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');

		$('.row-type-4:first', this).addClass('row-type-4-img');
		$('.row-type-4:last', this).after('<tr><td class="type-spacer type-spacer-bold" colspan="4"></td></tr>');
		
		$('.row-type-5:first', this).addClass('row-type-5-img');
		$('.row-type-5:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');
		
		$('.row-type-6:first', this).addClass('row-type-6-img');
		$('.row-type-6:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');
		
		$('.row-type-7:first', this).addClass('row-type-7-img');
		$('.row-type-7:last', this).after('<tr><td class="type-spacer" colspan="4"></td></tr>');
		
		$('.row-type-8:first', this).addClass('row-type-8-img');
	});
	
	if (panel.length) panelW = panel.width();
	else panelW = wrapperW - (panel.length?panel.outerWidth(true)-panel.width():40); // wrapper - margins
	
	newPanel.prependTo(this.container);
	panel.css({ position: 'absolute', zIndex: 100, left: 0, top: 0, width: panelW }).animate({ opacity: 0 }, 'fast', 'linear', function(){ panel.remove(); });
	
	newPanel.prepend('<div class="week-stats">' + this.getStats(data) + '</div>');
	this.adjustStatsBoxes();
	
	$('#day_'+(new Date().toStr())).addClass('today');									// add class if today
//	this.initEvents();
};


App.Week.adjustStatsBoxes = function(){
	var week = $('#wrapper .week:first'), pane = week.find('.week-stats'), boxes = week.find('.week-stats .stats-box'), cols = (boxes.length < 4 ? boxes.length : 4), h = 0, i = 0, box;
	for (; box = boxes[i++] ;) h = Math.max(h, $(box).height());
	boxes.width((pane.width()) / cols - 22).height(h);
};

App.Week.getStats = function(days){
	var i = 0, day, row, rows = [], data = {};
	
	for(; day = days[i++] ;) $.merge(rows, day.rows);				// flattten the data array
	
	for (i=0; row = rows[i++] ;){									// create user-based array of projects, i.e.: data: { userName: { 'worklog': 5 } }
		data[row.userName] = data[row.userName] || {};
		data[row.userName][row.projectName] = (data[row.userName][row.projectName] || 0) + 1;
	}
	
	var statsHtml = '', usr = '', proj = '';
	for (usr in data){
		if (!data.hasOwnProperty(usr)) continue;
		statsHtml += '<div class="stats-box"><b>' + usr + '</b> spent <ul>';
		for (proj in data[usr]){
			if (!data[usr].hasOwnProperty(proj)) continue;
			//statsHtml += '<li><b>' + data[usr][proj] + '</b> hours on <b>' + proj + '</b>';
			statsHtml += '<li><b>' + (data[usr][proj]/8) + '</b> days (' + data[usr][proj] +'h) on <b>' + proj + '</b>';
		}
		statsHtml += '</ul></div>';
	}
	
	return statsHtml;
};
/*** WEEK ACTIONS **************************************************************************************************************/
